<?php
// @filesource upfile.php
// 上传文件
header("Content-Type:text/html;charset=UTF-8");
define('_UPLOAD_DIR', 'pub'.DIRECTORY_SEPARATOR);

/**
 * 上传文件
 *
 * 返回值:
 *  0 文件类型错误
 * 	
 * 
 */
function upFile(){
	if( empty($_FILES['file']['size']) ) return 0;
	set_time_limit(0);
	$fileType = array("jpg","gif","bmp","jpeg","png");
	
	//新建文件夹..  sdq/pub/2009/12/
	$year = _UPLOAD_DIR.date('Y');
	$month = $year.DIRECTORY_SEPARATOR.date('m');
	if( !is_dir($year) ){
		mkdir($year);
	}
	if( !is_dir($month) ){
		mkdir($month);
	}
	$pub_dir = $month.DIRECTORY_SEPARATOR;
	
	$a = strtolower(fileext($_FILES['file']['name']));
	//判断文件类型
	if(!in_array( strtolower(fileext($_FILES['file']['name'])), $fileType )) {
		//$text=implode(",",$fileType);
    	return 2; //echo "您只能上传以下类型文件: ",$text,"<br>";
	} else{ //生成目标文件的文件名   
   		$filename=explode(".",$_FILES['file']['name']);
   	
   	do{ 
   		$filename[0]=random(10); //设置随机数长度
     	$name=implode(".",$filename);
     	//$name1=$name.".Mcncc";
     	$uploadfile = $pub_dir.$name;
     	// echo $uploadfile.'<br />'.$_FILES['file']['tmp_name'].'<br />';
   }while(file_exists($uploadfile));

   try {
   	if ( move_uploaded_file($_FILES['file']['tmp_name'],$uploadfile) ){
		//$pubfile = str_replace($_SERVER['DOCUMENT_ROOT'], "http://localhost", $uploadfile);
       	return $uploadfile;
   		}
   }catch (Exception $e){
   		echo $e->getMessage();
   }
	}
	return 0;
}//END func upFile

//获取文件后缀名函数
function fileext($filename){
	return substr(strrchr($filename, '.'), 1);
}
//生成随机文件名函数   
function random($length){
	$hash = 'kkyoo-ld-';
	$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
	$max = strlen($chars) - 1;
	mt_srand((double)microtime() * 1000000);
	for($i = 0; $i < $length; $i++){
		$hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}


// ------------   开始文件上传  -----------------------
var_dump($_POST);
	$ip = $_SERVER['REMOTE_ADDR'];
	$succeed = false;
	$file = '';
	$date = date('Y-m-d H:i:s');

if( isset($_POST['submit']) ){
	
	if( $file = upFile() ){
		$succeed = true;
	}else{
		$file = 'FAILED';
	}
	$file .= ' <-- '.$_FILES['file']['name'];
	
}else{
	$file = 'NULL';
}

$log = ':: '.$succeed.' :: '.$date.' :: '.$ip.' :: '.$file."\n";
error_log($log,3,'pub'.DIRECTORY_SEPARATOR.'upfiles.log');

?>

<form id="uploadFrom" name="uploadFrom" method="post" enctype="multipart/form-data" action="upfile.php" >
	<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
	<label>选择需上传的文件： <input name="file" type="file" value="浏览" ></label>&nbsp;&nbsp;
	<label>文件说明: <input type="text" value="" name="desc" maxlength="50" /></label>&nbsp;&nbsp;
    <input type="submit" value="上传" name="submit">
</form>

